import axios from 'axios';

// api
let baseURL = 'http://zljypt.swu.edu.cn/a';
// let baseURL = 'http://localhost:13200';
// let baseURL = 'http://39.104.58.152:8900';
let apiURL = baseURL + '/web/v2/api';

let http = axios.create({
  baseURL: apiURL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8;'
  }
});

let requestCount = 0;

// loading操作
const ShowLoading = () => {
  if (requestCount === 0) {
    document.getElementById('ui-loading').style.display = 'block';
  }
  requestCount++;
};
const HideLoading = () => {
  requestCount--;
  if (requestCount <= 0) {
    requestCount = 0;
    document.getElementById('ui-loading').style.display = 'none';
  }
};

http.interceptors.request.use(config => {
  return config;
});

http.interceptors.response.use(
  response => {
    HideLoading();
    return response.data;
  },
  error => {
    HideLoading();
    return Promise.reject(error);
  }
);

const get = (url, params, showLoading = true) => {
  return new Promise((resolve, reject) => {
    showLoading && ShowLoading();
    http
      .get(url, { params })
      .then(res => {
        resolve(res);
      })
      .catch(error => {
        reject(error);
      });
  });
};

const post = (url, params, showLoading = true) => {
  return new Promise((resolve, reject) => {
    showLoading && ShowLoading();
    http
      .post(url, params)
      .then(res => {
        resolve(res);
      })
      .catch(error => {
        reject(error);
      });
  });
};

export { get, post, baseURL };
